function autostop1()
% autostop1 - algorithm prototype
% operates reading movie from current directory

% ================================
% ---------------------
% constants

% file paths
movieavi		= 'movie.avi';
backgroundavi	= 'background.avi';
segmentedavi	= 'segmented.avi';
outputavi		= 'out.avi';

% --------------------
% parameters
bgfactor		= 0.05;		% background factor
segmentsize 	= 8;		% segment sie (pixels)
fgtreshold		= 0.3;		% bg/fg luminance difference factor
grouptreshold	= 0.05;		% segment value treshold to make it a group

mingroupsize	= 30;		% min group size to consider it a interesting object
maxgroupdistance = 30;		% max distance between occurences of group (in pixels) to consider it identical - naive group matching

% ================================
% -------------------
% read movie
global movie_cache;

% try to load from cache
disp('loading movie');
if size( movie_cache, 2 ) > 0
	movie = movie_cache;
else
	disp('from file...');
	movie = aviread( movieavi ); % this is crutial. if this will ail, everything fails
	movie_cache=movie;
end

% read or create backround
global background_cache;
disp('loading background');
if size( background_cache, 2 ) > 0
	background = background_cache;
else
	try
			disp('trying to load background avi');
		background = aviread( backgroundavi );
	catch
		% create and store background
			disp('unable to load background avi, generating');
		background = avibackground( movie, bgfactor );
			disp('saving into file');
		movie2avi( background, backgroundavi );
	end
	background_cache = background;
end
	
% read or create segment movie
% read or create backround
global segment_cache;
disp('loading segments');
if size( segment_cache, 2 ) > 0
	segmented = segment_cache;
else
	try
			disp('trying to load segments avi');
		segmented = aviread( segmentedavi );
	catch
		% create and store background
			disp('unable to load segmented avi, generating');
		segmented = avisegment( movie, bgfactor, fgtreshold, segmentsize );
			disp('saving into file');
		movie2avi( segmented, segmentedavi );
	end
	segment_cache = segmented;
end
	
% ------------------------
% analyze

global groups;

disp('Starting analyze');
frames = size( movie, 2 );
groups = cell( frames, 1 ); % groups for frames

for frame = 1:(frames-1)
	% report progress
	disp( sprintf('%d/%d', frame, frames) );
	
	% get images
	img = movie(frame).cdata;
	bak = background(frame).cdata;
	seg = segmented(frame).cdata;
	
	% get groups in segments luminance
	frame_groups = findgroups( lumin( seg ), 1 , grouptreshold );
	
	% filter smaller
	frame_groups = filtersmaller( frame_groups, mingroupsize / segmentsize );
	
	groupsnum = size( frame_groups, 1 );
	
	% store groups in genral cell array
	groups{ frame } = frame_groups;
	
	
	% show image and groups
	paintgroups( frame_groups, img, segmentsize );
	
	% paint group traces
	% seek for identity groups
	if frame > 1
		connect_groups( frame, maxgroupdistance );
		hold on;
		painttraces( frame, segmentsize );
		hold off;
	end
	
	% pause to let images be shown
	pause(0.1);
	
	
end	% frame:framesend

% ================================== filtersmaller =========================
function filtered = filtersmaller( groups, minsize )
% filters groups smaller than size


filtered = [];

for i = 1:size(groups,1)
	g = groups(i);
	
	if ( g.maxX - g.minX > minsize ) || ( g.maxY - g.minY > minsize )
		filtered = [ filtered; g ];
	end
end


% ==================================== connect groups =====================
function connect_groups( frame, maxgroupdistance );
% connects groups from global var 'groups'

global groups;

currgroups = size( groups{frame}, 1 );
prevgroups = size( groups{frame-1}, 1 );


for group = 1:currgroups
	% get distances to prev groups
	distances = [];
	for prev = 1:prevgroups
		dist = abs( groups{frame}(group).centerX - groups{frame-1}(prev).centerX ) + ...
			abs( groups{frame}(group).centerY - groups{frame-1}(prev).centerY );
		distances = [ distances; dist ];
	end
	
	% select closest
	groups{frame}(group).previous = 0;
	if size( distances, 1 ) > 0
		[ds, di ] = sort(distances);
		if ds(1) < maxgroupdistance
			groups{frame}(group).previous = di(1);
			disp( sprintf('f: %d, %d>%d', frame, di(1), group ));
		end
	end
end

% ============================== paint traces ============================
function painttraces( frame, factor )
% paint group traces from global 'groups', going back from 'frame'
	
global groups;

currgroups = size( groups{frame}, 1 );

for group = 1:currgroups
	xs = [];
	ys = [];
	g = group;
	for prev = frame:-1:1
		if groups{prev}(g).previous > 0
			xs = [ xs groups{prev}(g).centerX ];
			ys = [ ys groups{prev}(g).centerY ];
			g = groups{prev}(g).previous;
		else
			break;
		end
	end
	
	% plot group trace
	if size(xs,1) > 0 
		plot( xs*factor, ys*factor, 'r' );
	end
end

